package com.licenta.fbApp.server;

import java.sql.ResultSet;
import java.util.ArrayList;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.licenta.fbApp.shared.DatabaseService;
import com.licenta.fbApp.shared.NotLoggedInException;
import com.licenta.fbApp.shared.Restaurant;

public class DatabaseServiceImpl  extends RemoteServiceServlet implements DatabaseService{

	private static final long serialVersionUID = 5742796160437323678L;
	/**
	 * @uml.property  name="conn"
	 * @uml.associationEnd  
	 */
	private DB_Connect conn;
	
	private void connect() 
	{
		//if ( conn != null )
			//return;
		conn = new DB_Connect();
	}
	
	public ArrayList<Restaurant> getRestaurants(String query){
		
		ArrayList<Restaurant> result = new ArrayList<Restaurant>();
		connect();
		if ( conn == null) {
			System.out.println("connection null");
			return null;
		}		
		ResultSet results = conn.execute(query); 			  
		try {
			while (results.next()) {
				result.add(new Restaurant(results.getString("Name"), results.getString("Address"), Double.parseDouble(results.getString("PriceRank")), Integer.parseInt(results.getString("Votes")), ""));  
			  }
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		
		conn.close();
		  System.out.println(result.size());
		return result;		
	}

	public String execute(String query) throws NotLoggedInException {
		connect();
		if ( conn == null) {
			System.out.println("connection null");
			return null;
		}		
		
		ResultSet results = conn.execute(query);
		try {
			return results.getString(0);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		return null;
	}
}
